package com.sunda.spmsorder.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunda.spmsorder.entity.OrderLog;
import com.sunda.spmsorder.mapper.OrderLogMapper;
import com.sunda.spmsorder.service.IOrderLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 订单审批记录表 服务实现类
 * </p>
 *
 * @author Wayne
 * @since 2021-02-03
 */
@Service
public class OrderLogServiceImpl extends ServiceImpl<OrderLogMapper, OrderLog> implements IOrderLogService {

    @Autowired
    OrderLogMapper orderLogMapper;

    @Override
    public void insertOrderLog(OrderLog orderLog) {
        orderLogMapper.insert(orderLog);
    }

    @Override
    public List<Map<String, Object>> orderLogList(String spmsWsId) {
        return orderLogMapper.getLogByOrderWsId(spmsWsId);
    }

    @Override
    public List<Map<String, Object>> orderLogLists(String spmsId) {
        return orderLogMapper.getLogByOrderWerksId(spmsId);
    }

    @Override
    public void saveOrderLog(String userId, String comments, String uuid) {
        OrderLog orderLog = new OrderLog();
        orderLog.setUuid(uuid);
        orderLog.setUserId(userId);
        orderLog.setComments(comments);
        orderLogMapper.insert(orderLog);
    }

    /**
     * 根据车间请购单号 或 工厂请购单号查询请购单据在SRM状态。
     * 请求的单据必须是 OA审批通过提交SRM 的单据，即关联的工厂请购单 工厂请购单SPMS状态 = 5，其余状态忽略。
     * orderType：1车间请购单，2工厂请购单；orderUuid 对应单号 UUID；
     * 示例 orderType = 2；orderUuid = 819eec3ca6a04548806e46d2ac742f07；
     * orderType = 1；orderUuid = 898388417b634b5387280ec773bce7e6 或 793598e3d20243de83c375f24b491599；
     * @param orderType
     * @param orderUuid
     * @return
     */
    @Override
    public List<Map<String, Object>> getOrderLogSrm(String orderType, String orderUuid) {
        if (StringUtils.isEmpty(orderType) || StringUtils.isEmpty(orderUuid)){
            return null;
        }
        if ("1".equals(orderType)){
            List<Map<String, Object>> getOrderWorkshopOrderLogSrm = orderLogMapper.getOrderWorkshopOrderLogSrm(orderUuid);
            if (getOrderWorkshopOrderLogSrm == null || getOrderWorkshopOrderLogSrm.size() == 0){
                return null;
            }
            if (getOrderWorkshopOrderLogSrm.get(0) == null || getOrderWorkshopOrderLogSrm.get(0).get("orderWerksStatus") == null){
                return null;
            }
            /** 车间请购单关联的工厂请购单单据状态需为 5-OA审批通过提交SRM 才有SRM日志，其余状态忽略 */
            if (!"5".equals(getOrderWorkshopOrderLogSrm.get(0).get("orderWerksStatus").toString())){
                return null;
            }
            return getOrderWorkshopOrderLogSrm;
        }

        List<Map<String, Object>> getOrderWerksOrderLogSrm = orderLogMapper.getOrderWerksOrderLogSrm(orderUuid);
        if (getOrderWerksOrderLogSrm.size() == 0) {
            return null;
        }
        if (!"5".equals(getOrderWerksOrderLogSrm.get(0).get("orderWerksStatus").toString())){
            return null;
        }
        return getOrderWerksOrderLogSrm;
    }

    /** 发送REST请求到ESB，数据格式化 */
    @Override
    public JSONObject formatDataSend(List<Map<String, Object>> orderWerksInfo){
        JSONObject doc = new JSONObject();
        JSONObject REQUEST = new JSONObject();
        JSONObject ESB_ATTRS = new JSONObject();
        JSONObject REQUEST_DATA = new JSONObject();

        ESB_ATTRS.put("App_ID", "SPMS");
        ESB_ATTRS.put("Application_ID", "00020000000002");
        ESB_ATTRS.put("Transaction_ID", UUID.randomUUID().toString());

        JSONArray Items = new JSONArray();
        for (Map<String, Object> map : orderWerksInfo){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("purchaseRequestNumber", map.get("orderWerksId"));
            jsonObject.put("requestItemNumber", map.get("orderWerksRowId"));
            Items.add(jsonObject);
        }
        REQUEST_DATA.put("Items", Items);
        REQUEST_DATA.put("Operation", "spms_srm_purchase_status");
        REQUEST_DATA.put("Type", "purchase_status");

        REQUEST.put("ESB_ATTRS", ESB_ATTRS);
        REQUEST.put("REQUEST_DATA", REQUEST_DATA);

        doc.put("REQUEST", REQUEST);
        return doc;
    }

    /**
     * ESB 请求后返回数据格式化处理后再返回给前端
     *  返回信息中状态 status 码值： 0 审批通过; 1 新建; 2 审批中; 3 审批拒绝; 4 已建询价; 5 已建竞价; 6 已建招标; 7 询价完成; 8 竞价完成; 9 招标完成;
     *  10 已建订单; 11 发货在途; 12 部分收货; 13 全部收货; 14 单次合同; 15 长期协议; 16 已发货; 17 已收货; 18 冻结; 21冻结;
     * @param received
     * @param mapList
     * @return
     */
    @Override
    public JSONArray formatDataReceived(String received, List<Map<String, Object>> mapList){
        try {
            JSONObject jsonObject = JSONObject.parseObject(received);
            System.out.println("jsonObject ======= " + jsonObject);
            if ("S".equals(jsonObject.getJSONObject("RESPONSE").getJSONObject("RETURN_DATA").getString("TYPE"))){
                JSONArray DATA = jsonObject.getJSONObject("RESPONSE").getJSONObject("RETURN_DATA").getJSONArray("DATA");
                JSONArray returnedData = new JSONArray();
                if (DATA.size() > 0){
                    for (int i = 0; i < DATA.size(); i ++){
                        JSONObject obj = DATA.getJSONObject(i);
                        String purchaseRequestNumber = obj.getString("purchaseRequestNumber");
                        String requestItemNumber = obj.getString("requestItemNumber");
                        String status = obj.getString("status");
                        String srmStatusDesc = "0".equals(status) ? "审批通过" : "1".equals(status) ? "新建" : "2".equals(status) ? "审批中" : "3".equals(status)
                                ? "审批拒绝" : "4".equals(status) ? "已建询价" : "5".equals(status) ? "已建竞价" : "6".equals(status) ? "已建招标" : "7".equals(status)
                                ? "询价完成" : "8".equals(status) ? "竞价完成" : "9".equals(status) ? "招标完成" : "10".equals(status) ? "已建订单" : "11".equals(status)
                                ? "发货在途" : "12".equals(status) ? "部分收货" : "13".equals(status) ? "全部收货" : "14".equals(status) ? "单次合同" : "15".equals(status)
                                ? "长期协议" : "16".equals(status) ? "已发货" : "17".equals(status) ? "已收货" : "18".equals(status) ? "冻结" : "21".equals(status)
                                ? "关闭" : "未知状态";
                        obj.put("srmStatusDesc", srmStatusDesc);
                        obj.put("procurementEngineer", obj.getString("fbk29"));
                        obj.put("procurementSpecialist", obj.getString("fbk32"));
                        obj.put("unlockReason", obj.getString("unlockReason"));
                        for (Map<String, Object> map : mapList){
                            if (map.get("orderWerksId").equals(purchaseRequestNumber) && map.get("orderWerksRowId").toString().equals(requestItemNumber)){
                                obj.put("orderWorkshopId", map.get("orderWorkshopId"));
                                obj.put("orderWorkshopRowId", map.get("orderWorkshopRowId"));
                                obj.put("materialNo", map.get("materialNo"));
                                obj.put("materialZhDesc", map.get("materialZhDesc"));
                                obj.put("approvalQty", map.get("approvalQty"));
                                obj.put("basicUnit", map.get("basicUnit"));
                            }
                        }
                        returnedData.add(obj);
                    }
                }
                if (returnedData.size() > 0){
                    return returnedData;
                }
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<Map<String, Object>> getOrderLogList(String uuid) {
        return orderLogMapper.getOrderLogList(uuid);
    }
}
